package tech.summerly.weather.data.local

import android.content.Context
import android.content.SharedPreferences
import androidx.core.content.edit
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.experimental.Deferred
import kotlinx.coroutines.experimental.async
import tech.summerly.weather.AppContext
import java.lang.reflect.Type

/**
 * Created by summer on 18-3-13
 */
abstract class Persistence {


    protected open val name = "weather"

    protected val preference: SharedPreferences by lazy {
        AppContext.instance.getSharedPreferences(name, Context.MODE_PRIVATE)
    }

    /**
     * 存放一个 Object 到数据库中，使用 Gson 进行序列化
     */
    protected fun putObject(key: String, any: Any?) = async {
        preference.edit {
            putString(key, Gson().toJson(any))
        }
    }

    /**
     * 从数据库中读取一个 Object
     */
    protected inline fun <reified T> getObject(key: String): Deferred<T?> {
        val type = object : TypeToken<T>() {}.type
        return getObject<T>(key, type)
    }

    protected fun <T> getObject(key: String, type: Type): Deferred<T?> = async {
        val json = preference.getString(key, null) ?: return@async null
        return@async Gson().fromJson<T>(json, type)
    }

}